import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
import { ActionName } from '@/napcat-onebot/action/router';
import { ChatType, Peer, ElementType } from 'napcat-core/types';
import fs from 'fs';
import { uriToLocalFile } from 'napcat-common/src/file';
import { SendMessageContext } from '@/napcat-onebot/api';
import { Static, Type } from '@sinclair/typebox';

const SchemaData = Type.Object({
  group_id: Type.Union([Type.Number(), Type.String()]),
  file: Type.String(),
  name: Type.String(),
  folder: Type.Optional(Type.String()),
  folder_id: Type.Optional(Type.String()), // 临时扩展
});

type Payload = Static<typeof SchemaData>;

interface UploadGroupFileResponse {
  file_id: string | null;
}

export default class GoCQHTTPUploadGroupFile extends OneBotAction<Payload, UploadGroupFileResponse> {
  override actionName = ActionName.GoCQHTTP_UploadGroupFile;
  override payloadSchema = SchemaData;

  async _handle (payload: Payload): Promise<UploadGroupFileResponse> {
    let file = payload.file;
    if (fs.existsSync(file)) {
      file = `file://${file}`;
    }
    const downloadResult = await uriToLocalFile(this.core.NapCatTempPath, file);
    const peer: Peer = {
      chatType: ChatType.KCHATTYPEGROUP,
      peerUid: payload.group_id.toString(),
    };
    if (!downloadResult.success) {
      throw new Error(downloadResult.errMsg);
    }
    const msgContext: SendMessageContext = {
      peer,
      deleteAfterSentFiles: [],
    };
    const sendFileEle = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, payload.folder ?? payload.folder_id);
    msgContext.deleteAfterSentFiles.push(downloadResult.path);
    const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, [sendFileEle], msgContext.deleteAfterSentFiles);

    const fileElement = returnMsg.elements.find(ele => ele.elementType === ElementType.FILE);
    return {
      file_id: fileElement?.fileElement?.fileUuid || null,
    };
  }
}
